package com.lookoutthebush.companyindex.services.impl;

import com.lookoutthebush.companyindex.dao.NewsDAO;
import com.lookoutthebush.companyindex.domain.NewsDO;
import com.lookoutthebush.companyindex.enums.NewsDeleteEnum;
import com.lookoutthebush.companyindex.enums.NewsReleaseEnum;
import com.lookoutthebush.companyindex.exception.BizException;
import com.lookoutthebush.companyindex.services.INewsService;
import com.lookoutthebush.companyindex.util.CheckUtil;
import com.lookoutthebush.companyindex.util.MyDate;
import com.lookoutthebush.companyindex.util.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class NewsServiceImpl implements INewsService {

    @Resource
    private NewsDAO newsDAO;

    /**
     * add
     *
     * @param newsDO do
     * @return id
     */
    @Override
    public Long createNews(NewsDO newsDO) {
        String filed = CheckUtil.isEmpty(newsDO, "userId", "typeId", "title", "content", "imageUrl", "source");
        if (!ObjectUtils.isEmpty(filed)) {
            throw new BizException(filed + "can not be null");
        }
        return newsDAO.insert(newsDO);
    }

    /**
     * 发布新闻
     *
     * @param id 主键id
     * @return boolean
     */
    @Override
    public boolean release(Long id) {
        if (null == id) {
            throw new BizException("id can not be null");
        }
        NewsDO newsDO = newsDAO.queryById(id);
        newsDO.setRelease(NewsReleaseEnum.YES.getValue());
        newsDO.setReleaseTime(MyDate.nowDateTimeString());
        return newsDAO.update(newsDO);
    }

    /**
     * 根据类型查询发布的未删除的新闻列表
     *
     * @param typeIds 分类ids
     * @return list
     */
    @Override
    public PageHelper<NewsDO> getReleaseListByPage(List<Long> typeIds, PageHelper<NewsDO> pageHelper) {
        if (ObjectUtils.isEmpty(typeIds)) {
            throw new BizException("id can not be null");
        }
        return newsDAO.queryValidListByPage(typeIds, NewsReleaseEnum.YES.getValue(), pageHelper);
    }

    /**
     * 根据类型查询未发布的未删除的新闻列表
     *
     * @param typeIds 分类ids
     * @return list
     */
    @Override
    public PageHelper<NewsDO> getNoReleaseListByPage(List<Long> typeIds, PageHelper<NewsDO> page) {
        if (ObjectUtils.isEmpty(typeIds)) {
            throw new BizException("id can not be null");
        }
        return newsDAO.queryValidListByPage(typeIds, NewsReleaseEnum.NO.getValue(), page);
    }

    @Override
    public boolean deleteById(Long id) {
        NewsDO newsDO = newsDAO.queryById(id);
        if(null == newsDO){
            return true;
        }
        newsDO.setDelete(NewsDeleteEnum.YES.getValue());
        newsDAO.update(newsDO);
        return true;
    }
}
